"""
需要导入第三方模块
cmd控制台输入以下命令并执行：
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pygame
"""
import random
import sys

import pygame
from pygame.locals import *

# 初始化pygame
pygame.init()
pygame.mixer.init()

# 游戏常量
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 500
TILE_SIZE = 50  # 地图块大小
BULLET_WIDTH = 8
BULLET_HEIGHT = 20
FPS = 60

# 方向常量
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3

# 颜色常量
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('坦克大战')

# 资源管理类
class ResourceManager:
    def __init__(self):
        self.images = {}
        self.sounds = {}
        self.fonts = {}
        self.load_resources()
    
    def load_resources(self):
        # 创建默认图片（用于替代缺失的资源）
        default_surface = pygame.Surface((TILE_SIZE, TILE_SIZE))
        default_surface.fill(RED)
        default_bullet = pygame.Surface((BULLET_WIDTH, BULLET_HEIGHT))
        default_bullet.fill(WHITE)
        
        # 安全加载图片的辅助函数
        def safe_load_image(path, is_bullet=False):
            try:
                img = pygame.image.load(path).convert_alpha()
                if is_bullet:
                    return pygame.transform.scale(img, (BULLET_WIDTH, BULLET_HEIGHT))
                else:
                    return pygame.transform.scale(img, (TILE_SIZE, TILE_SIZE))
            except Exception as e:
                print(f"无法加载图片 {path}: {e}")
                return default_bullet if is_bullet else default_surface.copy()
        
        try:
            # 加载坦克图片
            # 英雄坦克
            self.images['hero_up'] = safe_load_image('images/hero_up.png')
            self.images['hero_right'] = safe_load_image('images/hero_right.png')
            self.images['hero_down'] = safe_load_image('images/hero_down.png')
            self.images['hero_left'] = safe_load_image('images/hero_left.png')
            
            # 简单坦克
            self.images['jian_up'] = safe_load_image('images/jian_up.png')
            self.images['jian_right'] = safe_load_image('images/jian_right.png')
            self.images['jian_down'] = safe_load_image('images/jian_down.png')
            self.images['jian_left'] = safe_load_image('images/jian_left.png')
            
            # 中等坦克
            self.images['zhong_up'] = safe_load_image('images/zhong_up.png')
            self.images['zhong_right'] = safe_load_image('images/zhong_right.png')
            self.images['zhong_down'] = safe_load_image('images/zhong_down.png')
            self.images['zhong_left'] = safe_load_image('images/zhong_left.png')
            
            # 难度坦克
            self.images['nan_up'] = safe_load_image('images/nan_up.png')
            self.images['nan_right'] = safe_load_image('images/nan_right.png')
            self.images['nan_down'] = safe_load_image('images/nan_down.png')
            self.images['nan_left'] = safe_load_image('images/nan_left.png')
            
            # 障碍物图片
            self.images['zhangai-zhalan'] = safe_load_image('images/zhangai-zhalan.png')
            
            self.images['zhangai-hunningtu'] = safe_load_image('images/zhangai-hunningtu.png')
            self.images['zhangai-hunningtu-huai'] = safe_load_image('images/zhangai-hunningtu-huai.png')
            
            self.images['zhangai-xiangzi'] = safe_load_image('images/zhangai-xiangzi.png')
            self.images['zhangai-xiangzi-huai'] = safe_load_image('images/zhangai-xiangzi-huai.png')
            
            self.images['zhangai-fangzi1'] = safe_load_image('images/zhangai-fangzi1.png')
            self.images['zhangai-fangzi1-huai'] = safe_load_image('images/zhangai-fangzi1-huai.png')
            self.images['zhangai-fangzi1-huai2'] = safe_load_image('images/zhangai-fangzi1-huai2.png')
            
            self.images['zhangai-fangzi2'] = safe_load_image('images/zhangai-fangzi2.png')
            self.images['zhangai-fangzi2-huai'] = safe_load_image('images/zhangai-fangzi2-huai.png')
            self.images['zhangai-fangzi2-huai2'] = safe_load_image('images/zhangai-fangzi2-huai2.png')
            
            # 老鹰图片
            self.images['ying1'] = safe_load_image('images/ying1.png')
            self.images['ying2'] = safe_load_image('images/ying2.png')
            self.images['ying3'] = safe_load_image('images/ying3.png')
            self.images['ying4'] = safe_load_image('images/ying4.png')
            
            # 子弹图片
            self.images['paodan1'] = safe_load_image('images/paodan1.png', True)
            self.images['paodan2'] = safe_load_image('images/paodan2.png', True)
            self.images['paodan3'] = safe_load_image('images/paodan3.png', True)
            self.images['paodan4'] = safe_load_image('images/paodan4.png', True)
            
            # 爆炸效果图片
            for i in range(1, 13):
                self.images[f'bomb{i}'] = safe_load_image(f'images/bomb{i}.png')
            
            # 加载音效
            try:
                self.sounds['background'] = pygame.mixer.Sound('sounds/background.mp3')
                self.sounds['hero_fire'] = pygame.mixer.Sound('sounds/hero_fire.wav')
                self.sounds['enemy_die'] = pygame.mixer.Sound('sounds/enemy_die.wav')
                self.sounds['eagle_destroyed'] = pygame.mixer.Sound('sounds/eagle_destroyed.wav')
            except Exception as e:
                print(f"无法加载音效: {e}")
                # 创建一个空的声音对象作为替代
                empty_sound = pygame.mixer.Sound(buffer=b'')
                self.sounds['background'] = empty_sound
                self.sounds['hero_fire'] = empty_sound
                self.sounds['enemy_die'] = empty_sound
                self.sounds['eagle_destroyed'] = empty_sound
            
            # 加载字体
            try:
                self.fonts['default'] = pygame.font.Font('fonts/msyh.TTF', 24)
            except Exception as e:
                print(f"无法加载字体: {e}")
                self.fonts['default'] = pygame.font.SysFont('arial', 24)  # 使用系统字体作为替代
        except Exception as e:
            print(f"加载资源时发生错误: {e}")
            # 确保至少有一些基本资源可用

# 游戏对象基类
class GameObject(pygame.sprite.Sprite):
    def __init__(self, resource_manager, x, y):
        super().__init__()
        self.resource_manager = resource_manager
        self.x = x
        self.y = y
        self.rect = pygame.Rect(x, y, TILE_SIZE, TILE_SIZE)
    
    def update(self):
        self.rect.x = self.x
        self.rect.y = self.y
    
    def draw(self, surface):
        pass

# 坦克基类
class Tank(GameObject):
    def __init__(self, resource_manager, x, y, speed, health, tank_type):
        super().__init__(resource_manager, x, y)
        self.speed = speed
        self.health = health
        self.max_health = health
        self.direction = DOWN
        self.tank_type = tank_type
        self.last_shot_time = 0
        self.shot_delay = 2000  # 射击延迟（毫秒）
        self.update_image()
    
    def update_image(self):
        if self.direction == UP:
            self.image = self.resource_manager.images[f'{self.tank_type}_up']
        elif self.direction == RIGHT:
            self.image = self.resource_manager.images[f'{self.tank_type}_right']
        elif self.direction == DOWN:
            self.image = self.resource_manager.images[f'{self.tank_type}_down']
        elif self.direction == LEFT:
            self.image = self.resource_manager.images[f'{self.tank_type}_left']
    
    def move(self, direction, obstacles):
        self.direction = direction
        self.update_image()
        
        old_x, old_y = self.x, self.y
        
        if direction == UP:
            self.y -= self.speed
        elif direction == RIGHT:
            self.x += self.speed
        elif direction == DOWN:
            self.y += self.speed
        elif direction == LEFT:
            self.x -= self.speed
        
        # 边界检测
        if self.x < 0:
            self.x = 0
        elif self.x > SCREEN_WIDTH - TILE_SIZE:
            self.x = SCREEN_WIDTH - TILE_SIZE
        
        if self.y < 0:
            self.y = 0
        elif self.y > SCREEN_HEIGHT - TILE_SIZE:
            self.y = SCREEN_HEIGHT - TILE_SIZE
        
        # 碰撞检测
        self.rect.x = self.x
        self.rect.y = self.y
        
        for obstacle in obstacles:
            if self.rect.colliderect(obstacle.rect):
                self.x, self.y = old_x, old_y
                self.rect.x = self.x
                self.rect.y = self.y
                return False
        
        return True
    
    def shoot(self):
        current_time = pygame.time.get_ticks()
        if current_time - self.last_shot_time > self.shot_delay:
            self.last_shot_time = current_time
            
            # 根据坦克方向确定子弹的初始位置
            if self.direction == UP:
                bullet_x = self.x + (TILE_SIZE - BULLET_WIDTH) // 2
                bullet_y = self.y - BULLET_HEIGHT
            elif self.direction == RIGHT:
                bullet_x = self.x + TILE_SIZE
                bullet_y = self.y + (TILE_SIZE - BULLET_HEIGHT) // 2
            elif self.direction == DOWN:
                bullet_x = self.x + (TILE_SIZE - BULLET_WIDTH) // 2
                bullet_y = self.y + TILE_SIZE
            elif self.direction == LEFT:
                bullet_x = self.x - BULLET_WIDTH
                bullet_y = self.y + (TILE_SIZE - BULLET_HEIGHT) // 2
            
            return Bullet(self.resource_manager, bullet_x, bullet_y, self.direction, self)
        
        return None
    
    def take_damage(self):
        self.health -= 1
        return self.health <= 0
    
    def draw(self, surface):
        surface.blit(self.image, (self.x, self.y))
        
        # 绘制血条
        health_bar_width = TILE_SIZE * (self.health / self.max_health)
        pygame.draw.rect(surface, RED, (self.x, self.y - 10, TILE_SIZE, 5))
        pygame.draw.rect(surface, GREEN, (self.x, self.y - 10, health_bar_width, 5))

# 英雄坦克类
class HeroTank(Tank):
    def __init__(self, resource_manager, x, y):
        super().__init__(resource_manager, x, y, 3, 1, 'hero')
        self.shot_delay = 200  # 200ms射击延迟
        self.lives = 3  # 英雄坦克有3条命
        self.initial_x = x  # 记录初始位置，用于重生
        self.initial_y = y

# 敌方坦克类
class EnemyTank(Tank):
    def __init__(self, resource_manager, x, y, tank_type):
        if tank_type == 'jian':
            super().__init__(resource_manager, x, y, 2, 1, 'jian')
            self.shot_delay = 3000  # 3秒射击延迟
        elif tank_type == 'zhong':
            super().__init__(resource_manager, x, y, 3, 2, 'zhong')
            self.shot_delay = 1500  # 1.5秒射击延迟
        elif tank_type == 'nan':
            super().__init__(resource_manager, x, y, 2, 3, 'nan')
            self.shot_delay = 1000  # 1秒射击延迟
        
        self.direction_change_time = 0
        self.direction_change_delay = random.randint(1000, 3000)  # 1-3秒随机改变方向
    
    def update(self, obstacles):
        current_time = pygame.time.get_ticks()
        
        # 随机改变方向
        if current_time - self.direction_change_time > self.direction_change_delay:
            self.direction = random.randint(0, 3)
            self.direction_change_time = current_time
            self.direction_change_delay = random.randint(1000, 3000)
        
        # 移动
        self.move(self.direction, obstacles)
        
        # 随机射击
        if random.random() < 0.01:  # 1%的概率尝试射击
            return self.shoot()
        
        return None

# 子弹类
class Bullet(GameObject):
    def __init__(self, resource_manager, x, y, direction, owner):
        super().__init__(resource_manager, x, y)
        self.direction = direction
        self.owner = owner
        self.speed = 5
        self.animation_index = 0
        self.animation_speed = 0.2
        self.animation_time = 0
        self.rect = pygame.Rect(x, y, BULLET_WIDTH, BULLET_HEIGHT)
        
        # 根据方向旋转子弹图片
        if direction == UP or direction == DOWN:
            self.image = resource_manager.images['paodan1']
        elif direction == DOWN:
            self.image = pygame.transform.rotate(resource_manager.images['paodan1'], 180)
        elif self.direction == RIGHT:
            self.image = pygame.transform.rotate(resource_manager.images['paodan1'], 270)
        else:  # LEFT or RIGHT
            self.image = pygame.transform.rotate(resource_manager.images['paodan1'], 90)
    
    def update(self):
        # 更新子弹位置
        if self.direction == UP:
            self.y -= self.speed
        elif self.direction == RIGHT:
            self.x += self.speed
        elif self.direction == DOWN:
            self.y += self.speed
        elif self.direction == LEFT:
            self.x -= self.speed
        
        self.rect.x = self.x
        self.rect.y = self.y
        
        # 子弹动画
        self.animation_time += self.animation_speed
        if self.animation_time >= 1:
            self.animation_time = 0
            self.animation_index = (self.animation_index + 1) % 4
            
            # 更新子弹图片
            bullet_img = self.resource_manager.images[f'paodan{self.animation_index + 1}']
            if self.direction == LEFT :
                self.image = pygame.transform.rotate(bullet_img, 90)
            elif  self.direction == RIGHT:
                self.image = pygame.transform.rotate(bullet_img, -90)
            else:
                self.image = bullet_img
        
        # 检查子弹是否超出屏幕
        if (self.x < 0 or self.x > SCREEN_WIDTH or 
            self.y < 0 or self.y > SCREEN_HEIGHT):
            return True  # 子弹需要被移除
        
        return False
    
    def draw(self, surface):
        surface.blit(self.image, (self.x, self.y))

# 障碍物类
class Obstacle(GameObject):
    def __init__(self, resource_manager, x, y, obstacle_type):
        super().__init__(resource_manager, x, y)
        self.obstacle_type = obstacle_type
        self.health = self.get_initial_health()
        self.update_image()
    
    def get_initial_health(self):
        if self.obstacle_type == 'zhalan':  # 栅栏
            return float('inf')  # 无限血量，不可摧毁
        elif self.obstacle_type == 'hunningtu':  # 混凝土
            return 2
        elif self.obstacle_type == 'xiangzi':  # 木箱
            return 2
        elif self.obstacle_type.startswith('fangzi'):  # 房子
            return 3
        return 0
    
    def update_image(self):
        if self.obstacle_type == 'zhalan':
            self.image = self.resource_manager.images['zhangai-zhalan']
        elif self.obstacle_type == 'hunningtu':
            if self.health == 2:
                self.image = self.resource_manager.images['zhangai-hunningtu']
            else:
                self.image = self.resource_manager.images['zhangai-hunningtu-huai']
        elif self.obstacle_type == 'xiangzi':
            if self.health == 2:
                self.image = self.resource_manager.images['zhangai-xiangzi']
            else:
                self.image = self.resource_manager.images['zhangai-xiangzi-huai']
        elif self.obstacle_type == 'fangzi1':
            if self.health == 3:
                self.image = self.resource_manager.images['zhangai-fangzi1']
            elif self.health == 2:
                self.image = self.resource_manager.images['zhangai-fangzi1-huai']
            else:
                self.image = self.resource_manager.images['zhangai-fangzi1-huai2']
        elif self.obstacle_type == 'fangzi2':
            if self.health == 3:
                self.image = self.resource_manager.images['zhangai-fangzi2']
            elif self.health == 2:
                self.image = self.resource_manager.images['zhangai-fangzi2-huai']
            else:
                self.image = self.resource_manager.images['zhangai-fangzi2-huai2']
    
    def take_damage(self):
        if self.health != float('inf'):  # 如果不是无限血量
            self.health -= 1
            self.update_image()
            return self.health <= 0
        return False
    
    def draw(self, surface):
        surface.blit(self.image, (self.x, self.y))

# 老鹰类
class Eagle(GameObject):
    def __init__(self, resource_manager, x, y):
        super().__init__(resource_manager, x, y)
        self.eagle_type = random.randint(1, 4)  # 随机选择老鹰图片
        self.image = resource_manager.images[f'ying{self.eagle_type}']
        self.destroyed = False
    
    def destroy(self):
        self.destroyed = True
    
    def draw(self, surface):
        surface.blit(self.image, (self.x, self.y))

# 爆炸效果类
class Explosion(GameObject):
    def __init__(self, resource_manager, x, y, size):
        super().__init__(resource_manager, x, y)
        self.size = size  # 'small' 或 'large'
        self.frame = 0
        self.max_frame = 11  # 爆炸效果有12帧，索引从0开始
        self.animation_speed = 0.5
        self.animation_time = 0
        
        # 根据爆炸大小调整尺寸
        if size == 'small':
            self.width = 8
            self.height = 8
        else:  # 'large'
            self.width = 60
            self.height = 60
        
        # 居中爆炸效果
        self.x = x + (TILE_SIZE - self.width) // 2
        self.y = y + (TILE_SIZE - self.height) // 2
        
        self.image = pygame.transform.scale(resource_manager.images[f'bomb{self.frame + 1}'], (self.width, self.height))
    
    def update(self):
        self.animation_time += self.animation_speed
        if self.animation_time >= 1:
            self.animation_time = 0
            self.frame += 1
            
            if self.frame > self.max_frame:
                return True  # 爆炸动画结束，需要移除
            
            self.image = pygame.transform.scale(self.resource_manager.images[f'bomb{self.frame + 1}'], (self.width, self.height))
        
        return False
    
    def draw(self, surface):
        surface.blit(self.image, (self.x, self.y))

# 游戏类
class Game:
    def __init__(self):
        self.resource_manager = ResourceManager()
        self.clock = pygame.time.Clock()
        self.running = True
        self.game_over = False
        self.victory = False
        self.score = 0
        self.tanks_destroyed = 0
        self.total_enemy_tanks = 30  # 总共需要摧毁的敌方坦克数量
        
        # 游戏对象
        self.hero = None
        self.eagle = None
        self.enemies = []
        self.obstacles = []
        self.bullets = []
        self.explosions = []
        
        # 加载地图
        self.load_map()
        
        # 播放背景音乐
        self.resource_manager.sounds['background'].play(-1)  # 循环播放
    
    def load_map(self):
        try:
            # 读取地图文件
            with open('map.txt', 'r') as f:
                map_data = f.readlines()
            
            # 解析地图数据
            for y, line in enumerate(map_data):
                tiles = line.strip().split()
                for x, tile in enumerate(tiles):
                    if x >= 20 or y >= 20:  # 防止地图过大
                        continue
                        
                    tile_x = x * TILE_SIZE
                    tile_y = y * TILE_SIZE
                    
                    try:
                        if tile == '0':  # 障碍物
                            self.obstacles.append(Obstacle(self.resource_manager, tile_x, tile_y, 'zhalan'))
                        elif tile == '2':  # 我方坦克出生点
                            self.hero = HeroTank(self.resource_manager, tile_x, tile_y)
                        elif tile == '3':  # 敌方坦克出生点
                            # 初始不创建敌方坦克，游戏开始后再创建
                            pass
                        elif tile == '4':  # 老鹰出生点
                            self.eagle = Eagle(self.resource_manager, tile_x, tile_y)
                        elif tile == '5':  # 房子1
                            self.obstacles.append(Obstacle(self.resource_manager, tile_x, tile_y, 'fangzi1'))
                        elif tile == '6':  # 房子2
                            self.obstacles.append(Obstacle(self.resource_manager, tile_x, tile_y, 'fangzi2'))
                        elif tile == '7':  # 混凝土
                            self.obstacles.append(Obstacle(self.resource_manager, tile_x, tile_y, 'hunningtu'))
                        elif tile == '8':  # 木箱
                            self.obstacles.append(Obstacle(self.resource_manager, tile_x, tile_y, 'xiangzi'))
                        elif tile == '9':  # 栅栏
                            self.obstacles.append(Obstacle(self.resource_manager, tile_x, tile_y, 'zhalan'))
                    except Exception as e:
                        print(f"加载地图元素错误: {e}")
                        continue
        except Exception as e:
            print(f"加载地图文件错误: {e}")
            # 如果地图加载失败，创建一个简单的默认地图
        
        # 如果地图中没有定义英雄坦克，则在默认位置创建
        if not self.hero:
            self.hero = HeroTank(self.resource_manager, 325, 450)
        
        # 如果地图中没有定义老鹰，则在默认位置创建
        if not self.eagle:
            self.eagle = Eagle(self.resource_manager, 425, 450)
        
        # 初始创建敌方坦克
        self.spawn_enemies(8)  # 初始生成8辆敌方坦克
    
    def spawn_enemies(self, count):
        # 敌方坦克出生点位置
        spawn_positions = [(0, 0), (SCREEN_WIDTH // 2 - TILE_SIZE // 2, 0), (SCREEN_WIDTH - TILE_SIZE, 0)]
        
        # 确保地图上敌方坦克数量不超过8个
        tanks_to_spawn = min(count, 8 - len(self.enemies))
        if tanks_to_spawn <= 0 or self.tanks_destroyed >= self.total_enemy_tanks:
            return
            
        for _ in range(tanks_to_spawn):
            # 最多尝试10次找到不重叠的位置
            max_attempts = 10
            for attempt in range(max_attempts):
                # 随机选择出生位置
                x, y = random.choice(spawn_positions)
                
                # 随机选择坦克类型
                tank_type = random.choice(['jian', 'zhong', 'nan'])
                
                # 创建敌方坦克
                enemy = EnemyTank(self.resource_manager, x, y, tank_type)
                
                # 检查是否与其他坦克重叠
                overlap = False
                for other_enemy in self.enemies:
                    if enemy.rect.colliderect(other_enemy.rect):
                        overlap = True
                        break
                
                if not overlap:
                    self.enemies.append(enemy)
                    break
                    
                # 如果尝试了最大次数仍然失败，就放弃这个坦克
                if attempt == max_attempts - 1:
                    print("无法找到合适的位置生成坦克")
                    break
    
    def handle_events(self):
        for event in pygame.event.get():
            if event.type == QUIT:
                self.running = False
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    self.running = False
                elif event.key == K_r and (self.game_over or self.victory):
                    self.__init__()  # 重新开始游戏
    
    def update(self):
        try:
            if self.game_over or self.victory:
                return
            
            # 处理键盘输入
            keys = pygame.key.get_pressed()
            
            # 创建碰撞对象列表（优化性能）
            collision_objects = self.obstacles.copy()
            # 只添加敌方坦克的矩形，而不是整个坦克对象
            for enemy in self.enemies:
                collision_objects.append(enemy)
            collision_objects.append(self.eagle)
            
            # 英雄坦克移动
            if keys[K_UP]:
                self.hero.move(UP, collision_objects)
            elif keys[K_RIGHT]:
                self.hero.move(RIGHT, collision_objects)
            elif keys[K_DOWN]:
                self.hero.move(DOWN, collision_objects)
            elif keys[K_LEFT]:
                self.hero.move(LEFT, collision_objects)
            
            # 英雄坦克射击
            if keys[K_SPACE]:
                bullet = self.hero.shoot()
                if bullet:
                    self.bullets.append(bullet)
                    try:
                        self.resource_manager.sounds['hero_fire'].play()
                    except Exception as e:
                        print(f"播放音效错误: {e}")
            
            # 更新敌方坦克
            enemies_copy = self.enemies.copy()  # 创建副本以避免迭代时修改列表
            for enemy in enemies_copy:
                if enemy in self.enemies:  # 确保坦克仍在列表中
                    # 为每个敌方坦克创建碰撞对象列表
                    enemy_collision_objects = self.obstacles.copy()
                    enemy_collision_objects.append(self.hero)
                    enemy_collision_objects.append(self.eagle)
                    for e in self.enemies:
                        if e != enemy:
                            enemy_collision_objects.append(e)
                    
                    bullet = enemy.update(enemy_collision_objects)
                    if bullet:
                        self.bullets.append(bullet)
            
            # 更新子弹
            bullets_to_remove = []
            for i, bullet in enumerate(self.bullets):
                if bullet.update():
                    bullets_to_remove.append(i)
                    continue
                
                # 检测子弹碰撞
                hit = False
                
                # 子弹与障碍物碰撞
                obstacles_copy = self.obstacles.copy()  # 创建副本以避免迭代时修改列表
                for obstacle in obstacles_copy:
                    if obstacle in self.obstacles and bullet.rect.colliderect(obstacle.rect):  # 确保障碍物仍在列表中
                        hit = True
                        if obstacle.take_damage():
                            self.obstacles.remove(obstacle)
                            self.explosions.append(Explosion(self.resource_manager, obstacle.x, obstacle.y, 'large'))
                        else:
                            self.explosions.append(Explosion(self.resource_manager, bullet.x, bullet.y, 'small'))
                        break
                
                if hit:
                    bullets_to_remove.append(i)
                    continue
                
                # 子弹与英雄坦克碰撞
                if bullet.owner != self.hero and bullet.rect.colliderect(self.hero.rect):
                    hit = True
                    if self.hero.take_damage():
                        self.hero.lives -= 1
                        self.explosions.append(Explosion(self.resource_manager, self.hero.x, self.hero.y, 'large'))
                        try:
                            self.resource_manager.sounds['enemy_die'].play()
                        except Exception as e:
                            print(f"播放音效错误: {e}")
                        
                        if self.hero.lives <= 0:
                            # 没有生命了，游戏结束
                            self.game_over = True
                        else:
                            # 还有生命，重生英雄坦克
                            self.hero.x = self.hero.initial_x
                            self.hero.y = self.hero.initial_y
                            self.hero.direction = UP
                            self.hero.health = self.hero.max_health
                    else:
                        self.explosions.append(Explosion(self.resource_manager, bullet.x, bullet.y, 'small'))
                
                # 子弹与敌方坦克碰撞
                if not hit:
                    enemies_copy = self.enemies.copy()  # 创建副本以避免迭代时修改列表
                    for enemy in enemies_copy:
                        if enemy in self.enemies and bullet.owner != enemy and bullet.rect.colliderect(enemy.rect):  # 确保坦克仍在列表中
                            hit = True
                            if enemy.take_damage():
                                self.enemies.remove(enemy)
                                self.explosions.append(Explosion(self.resource_manager, enemy.x, enemy.y, 'large'))
                                try:
                                    self.resource_manager.sounds['enemy_die'].play()
                                except Exception as e:
                                    print(f"播放音效错误: {e}")
                                self.score += 100
                                self.tanks_destroyed += 1
                                
                                # 检查是否胜利
                                if self.tanks_destroyed >= self.total_enemy_tanks:
                                    self.victory = True
                                else:
                                    # 生成新的敌方坦克
                                    self.spawn_enemies(1)
                            else:
                                self.explosions.append(Explosion(self.resource_manager, bullet.x, bullet.y, 'small'))
                            break
                
                # 子弹与老鹰碰撞
                if not hit and bullet.rect.colliderect(self.eagle.rect):
                    hit = True
                    self.eagle.destroy()
                    self.game_over = True
                    self.explosions.append(Explosion(self.resource_manager, self.eagle.x, self.eagle.y, 'large'))
                    try:
                        self.resource_manager.sounds['eagle_destroyed'].play()
                    except Exception as e:
                        print(f"播放音效错误: {e}")
                
                if hit:
                    bullets_to_remove.append(i)
            
            # 移除需要删除的子弹（从后往前删除，避免索引错误）
            for i in sorted(bullets_to_remove, reverse=True):
                if i < len(self.bullets):
                    self.bullets.pop(i)
            
            # 更新爆炸效果
            explosions_to_remove = []
            for i, explosion in enumerate(self.explosions):
                if explosion.update():
                    explosions_to_remove.append(i)
        except Exception as e:
            print(f"游戏更新错误: {e}")
            import traceback
            traceback.print_exc()
        
        # 移除完成的爆炸效果
        for i in sorted(explosions_to_remove, reverse=True):
            if i < len(self.explosions):
                self.explosions.pop(i)
    
    def draw(self):
        try:
            # 清空屏幕
            screen.fill(BLACK)
            
            # 绘制障碍物
            for obstacle in self.obstacles:
                try:
                    obstacle.draw(screen)
                except Exception as e:
                    print(f"绘制障碍物错误: {e}")
            
            # 绘制老鹰
            try:
                self.eagle.draw(screen)
            except Exception as e:
                print(f"绘制老鹰错误: {e}")
            
            # 绘制英雄坦克
            try:
                self.hero.draw(screen)
            except Exception as e:
                print(f"绘制英雄坦克错误: {e}")
            
            # 绘制敌方坦克
            for enemy in self.enemies:
                try:
                    enemy.draw(screen)
                except Exception as e:
                    print(f"绘制敌方坦克错误: {e}")
            
            # 绘制子弹
            for bullet in self.bullets:
                try:
                    bullet.draw(screen)
                except Exception as e:
                    print(f"绘制子弹错误: {e}")
            
            # 绘制爆炸效果
            for explosion in self.explosions:
                try:
                    explosion.draw(screen)
                except Exception as e:
                    print(f"绘制爆炸效果错误: {e}")
            
            # 绘制游戏信息
            try:
                score_text = self.resource_manager.fonts['default'].render(f'分数: {self.score}', True, WHITE)
                tanks_text = self.resource_manager.fonts['default'].render(f'已摧毁: {self.tanks_destroyed}/{self.total_enemy_tanks}', True, WHITE)
                screen.blit(score_text, (10, 10))
                screen.blit(tanks_text, (10, 40))
                
                # 绘制英雄坦克剩余生命数
                lives_text = self.resource_manager.fonts['default'].render(f'生命:', True, WHITE)
                screen.blit(lives_text, (SCREEN_WIDTH - 150, 10))
                
                # 使用坦克图标显示剩余生命数
                tank_icon = pygame.transform.scale(self.resource_manager.images['hero_up'], (20, 20))
                for i in range(self.hero.lives):
                    screen.blit(tank_icon, (SCREEN_WIDTH - 80 + i * 25, 20))
            except Exception as e:
                print(f"绘制游戏信息错误: {e}")
            
            # 绘制游戏结束或胜利信息
            try:
                if self.game_over:
                    game_over_text = self.resource_manager.fonts['default'].render('游戏结束! 按R键重新开始', True, RED)
                    text_rect = game_over_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))
                    screen.blit(game_over_text, text_rect)
                elif self.victory:
                    victory_text = self.resource_manager.fonts['default'].render('胜利! 按R键重新开始', True, GREEN)
                    text_rect = victory_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))
                    screen.blit(victory_text, text_rect)
            except Exception as e:
                print(f"绘制游戏状态信息错误: {e}")
            
            # 更新屏幕
            pygame.display.flip()
        except Exception as e:
            print(f"绘制游戏画面错误: {e}")
            import traceback
            traceback.print_exc()
    
    def run(self):
        try:
            while self.running:
                try:
                    self.clock.tick(FPS)
                    self.handle_events()
                    self.update()
                    self.draw()
                except Exception as e:
                    print(f"游戏循环错误: {e}")
                    import traceback
                    traceback.print_exc()
                    # 短暂暂停，避免错误消息刷屏
                    pygame.time.delay(100)
        except Exception as e:
            print(f"游戏主循环致命错误: {e}")
            import traceback
            traceback.print_exc()
        finally:
            pygame.quit()
            sys.exit()

# 主函数
def main():
    game = Game()
    game.run()

if __name__ == '__main__':
    main()